package com.ruoyi.web.controller.store.plan;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ApproveMission;
import com.ruoyi.common.core.domain.entity.StorePlan;
import com.ruoyi.common.core.domain.entity.Vendor;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ApproveService;
import com.ruoyi.system.service.StorePlanService;
import com.ruoyi.system.service.VendorService;
import com.ruoyi.system.service.resp.StorePlanDTO;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/8/12
 **/
@RestController
@RequestMapping("/store/plan/normal")
public class NormalPlanController extends BaseController {
    @Resource
    private StorePlanService storePlanService;

    @Resource
    private VendorService vendorService;

    @Resource
    private ApproveService approveService;

    @Log(title = "点餐采购计划导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StorePlan storePlan)
    {
        storePlan.setType("点餐");
        List<StorePlan> storePlans = storePlanService.selectList(storePlan).stream()
                .filter(v -> "启用".equals(v.getStatus()))
                .collect(Collectors.toList());
        List<StorePlanDTO> storePlanDTOS = fillToDTO(storePlans);
        ExcelUtil<StorePlanDTO> util = new ExcelUtil<StorePlanDTO>(StorePlanDTO.class);
        util.exportExcel(response, storePlanDTOS, "点餐采购计划");
    }

    @Log(title = "查询人员管理", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(StorePlan storePlan)
    {
        startPage();
        storePlan.setType("点餐");
        List<StorePlan> list = storePlanService.selectList(storePlan);
        return getDataTable(fillToDTO(list));
    }

    @Log(title = "查询人员管理All", businessType = BusinessType.OTHER)
    @GetMapping("/listAll")
    public TableDataInfo listAll(StorePlan storePlan)
    {
        storePlan.setType("点餐");
        List<StorePlan> list = storePlanService.selectList(storePlan);
        return getDataTable(list);
    }
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return success(storePlanService.selectById(id));
    }

    @Log(title = "新增人员管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody StorePlan storePlan)
    {
        storePlan.setType("点餐");
        storePlan.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        storePlan.setArea(SecurityUtils.getUserLocation());
        Boolean result = storePlanService.create(storePlan);
        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "修改人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody StorePlan storePlan) {
        storePlan.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = storePlanService.update(storePlan);
        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "删除人员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        return toAjax(storePlanService.deleteById(id));
    }

    private List<StorePlanDTO> fillToDTO(List<StorePlan> storePlans) {
        PageInfo<StorePlan> oldPage = new PageInfo<>(storePlans);
        Page<StorePlanDTO> newPage = new Page<>();
        newPage.setTotal(oldPage.getTotal());
        if (CollectionUtils.isEmpty(storePlans)) {
            return Collections.emptyList();
        }
        List<Long> vendorIds = storePlans.stream().filter(Objects::nonNull).map(StorePlan::getVendorId).collect(Collectors.toList());
        List<Vendor> vendors = vendorService.selectByIds(vendorIds);
        Map<Long, Vendor> vendorMap;
        if (CollectionUtils.isEmpty(vendors)) {
            vendorMap = new HashMap<>();
        } else {
            vendorMap = vendors.stream().collect(Collectors.toMap(Vendor::getId, v -> v));
        }
        storePlans.forEach(s -> {
            StorePlanDTO storePlanDTO = new StorePlanDTO();
            storePlanDTO.setId(s.getId());
            storePlanDTO.setPlanId(s.getPlanId());
            storePlanDTO.setPlanTime(s.getPlanTime());
            storePlanDTO.setName(s.getName());
            storePlanDTO.setVendorId(s.getVendorId());
            storePlanDTO.setVendorName(Optional.ofNullable(vendorMap.get(s.getVendorId())).map(Vendor::getName).orElse(null));
            storePlanDTO.setStatus(s.getStatus());
            storePlanDTO.setType(s.getType());
            storePlanDTO.setCreateBy(s.getCreateBy());
            storePlanDTO.setCreateTime(s.getCreateTime());
            storePlanDTO.setUpdateBy(s.getUpdateBy());
            storePlanDTO.setUpdateTime(s.getUpdateTime());
            storePlanDTO.setRemark(s.getRemark());
            storePlanDTO.setArea(s.getArea());
            ApproveMission approveMission = approveService.getByActivityd(s.getId(), "采购计划详情审批");
            if (approveMission == null) {
                storePlanDTO.setApproveStatus("未提交审批");
            } else {
                storePlanDTO.setApproveStatus(approveMission.getStatus());
                storePlanDTO.setApproveMissionId(approveMission.getId());
            }
            newPage.add(storePlanDTO);
        });
        return newPage;
    }
}
